package com.fnfn.sdk.api.shiro;

import com.fnfn.sdk.api.dao.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fnfn.sdk.api.entity.User;

public class UserRealm extends AuthorizingRealm {
    private final static Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        LOGGER.info("-----------------登录认证------------{}", authenticationToken);
        try {
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            String username = token.getUsername();
            User u = userMapper.selectByUsername(username);
            if (StringUtils.isNotEmpty(username)) {
                return new SimpleAuthenticationInfo(username, u.getcPassword(), "");
            }
            return null;
        } catch (Exception e) {
            LOGGER.error("", e);
            return null;
        }
    }
}
